﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Sx.Web.Admin.Areas.Sys.Models;
using Sx.Web.Framework;

namespace Sx.Web.Admin.Areas.Sys.Controllers
{
    [Area("sys")]
    public class MenuController : BaseController
    {
        private MenuService menuService = new MenuService();
        /// <summary>
        /// 菜单管理
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            ViewBag.Title = "菜单管理";
            return View();
        }

        /// <summary>
        /// 菜单管理
        /// </summary>
        /// <returns></returns>
        public IActionResult Indexajax() {
            var menuList = menuService.GetList<dynamic>(new { }, "menu_id,name,icon,url,parent_id,sort", "sort");
            List<object> rows = new List<object>();
            foreach (var d in menuList)
            {
                if (d.parent_id == 0)
                {
                    rows.Add(new { d.menu_id, iconCls = d.icon, d.name, d.url, orderNum = d.sort });
                }
                else
                {
                    rows.Add(new { d.menu_id, _parentId = d.parent_id, iconCls = d.icon, d.name, d.url, orderNum = d.sort });
                }
            }
            return Json(new { total = menuList.Count, rows = rows });
        }
        /// <summary>
        /// 获取数据源的树型结构
        /// </summary>
        /// <returns></returns>
        public IActionResult GetMenuTreeDS()
        {
            return Json(menuService.GetAllMenusForDS());
        }

        public IActionResult Edit(int id=0)
        {
            if (id == 0)
            {
                return View(new { title = "添加", data = new { menu_id = 0, name="", icon="", url="",parent_id = 0, sort=0 } });
            }
            return View(new
            {
                title = "编辑",
                data = menuService.Single(@"menu_id,name,icon,url,parent_id,sort",
                                            new { menu_id = id })
            });
        }

        public IActionResult EditAjax()
        { 
            var result = menuService.SaveByForm(Request, @"parent_id,name,icon,url,sort",  "menu_id", "menu_id");
            if (result > 0)
            {
                return GetSuccessResult();
            }
            return GetErrorResult(); 
        }
    }
}